from nio import (AsyncClient, ClientConfig, DevicesError, Event,InviteEvent, LoginResponse,
                 LocalProtocolError, MatrixRoom, MatrixUser, RoomMessageText,crypto, exceptions, RoomSendResponse)         
import re
import json 
class bot:
    cl=''
    def __init__(self,client:AsyncClient):
        self.cl=client
        print('Message Handler initiated')

    async def print_help(self,param,roomid):
        body="<h4>Usage manual for auto_tag_bot</h4> "
        body+="<br>Use !autotag_help to print this.<br>"
        body+="<br>Use !autotag_list to print configured autotags <br>"
        body+="<br>Use !autotag_add to to add an autotag with the following allowed syntax: <br>"
        body+="/plain !autotag_add name regex tag_list room_id<br>"
        body+="Where:"
        body+="<ul><li>name - unique name for autotag rule</li>"
        body+="<li>regex - is a reqular expresion without quotes i.e. ^word.*$</li>"
        body+="<li>tag_list - is a a comma separated list of user to tag on match i.e @user1:server1.org,@user2:server2.com</li>"
        body+="<li>room_id - is an id of a room where you want autotagging to fire, autotag_bot and at least one user from the tag_list must be present in the room for this to work. </li>"
        body+="<li>/plain - should be used always but is required only if using characters interpreted by markdown</li></ul>"
        await self.cl.send_msg_to_room(body,roomid)

    async def list_auto_tags(self,room_id):
        with open("auto_tagger.json", "r") as f:
            rules=json.load(f)
        f.close
        body='<h4>List of autotag rules:</h4>'
        for i in rules:
            body+=i+"<ul>"
            for x,y in rules.get(i).items():
                if isinstance(y, str):
                    body+="<li>"+x+" - "+y+"</li>"
                else:
                    body+="<li>"+x+" - "
                    for k in y:
                        body+=k+" "

                    body+="</li>"
            body+="</ul>"
        await self.cl.send_msg_to_room(body,room_id)



    async def add_auto_tag(self,match_id,regEx,tags,room_id):
        build_rule={}
        build_rule["match_id"]=match_id
        build_rule["regex"]=regEx
        build_rule["tags"]=tags
        build_rule["room_id"]=room_id

        with open("auto_tagger.json", "r") as f:
            rules=json.load(f)
        f.close
        rules[match_id]=build_rule

        with open("auto_tagger.json", "w") as f:
            f.write(json.dumps(rules))
        f.close

    async def send_auto_tag(self,roomid,tag,match):
        body="Tagging in : "
        for i in tag:
            body+=" <a href=\"https://matrix.to/#/"+i+"\">"+i+"</a>" ##NEED TO ADD TAGGING SYNTAX
        body+=" . Based on defined match: "+match
        await self.cl.send_msg_to_room(body,roomid)


    async def msg_event_fired(self,room: MatrixRoom, event: RoomMessageText):
        #menu logic here fires cl.send_msg_to_room
        print("Got message in "+room.room_id+" with "+event.body+" as content" )
        commandList=''
        commandDef=''
        taglist=[]
        if event.source.get("sender") == self.cl.user_id:
            return
        with open("auto_tagger.json", "r") as f:
            rules=json.load(f)
            for i in rules:
                if rules.get(i).get("room_id") == room.room_id:
                    if re.search(rules.get(i).get("regex"),event.body):
                        for y in room.users:
                            if y in rules.get(i).get("tags"):
                                taglist.append(y)
                        await self.send_auto_tag(room.room_id,taglist,rules.get(i).get("match_id"))





        if re.search(r"^!",event.body) :
            commandList=re.split("\s",event.body)
            commandDef=commandList[0]
        if commandDef == "!autotag_help":
            await self.print_help(commandList[1:len(commandList)],room.room_id)
        if commandDef == "!autotag_add":
            #VALIDATION!!!!
            m_id=commandList[1]
            regex=commandList[2]
            room_id=commandList[4]
            tgs=re.split(",",commandList[3])


            await self.add_auto_tag(m_id,regex,tgs,room_id)
            body="Added new autotag for room "+room_id+" based on given regex for "
            for l in tgs:
                body+=l+" "
            await self.cl.send_msg_to_room(body,room.room_id)
        if commandDef == "!autotag_list":
            await self.list_auto_tags(room.room_id)
